# -*- coding: utf-8 -*-
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
if __name__=="__main__":
    print('----------Vitesco ECU Damper Check Starting---------')
    from general_utils import clsCamera
    from cores import object_detect   
    from general_utils import myfunc
    import mydatafeeder
    import myfsm as fsm
    import cv2 
    
    print('>> Modules import done.')
    PBTXT_PATH=r'../model/saved_model.pbtxt'
    SAVED_MODEL_DIR=r'../model/ecu_damper_789/saved_model'
    confJson=r'config.json'
    labelClassJson=r'label_class.json'
    #-----------------相机线程--------------
    camera=clsCamera.clsGeneralCamera(clsCamera.CAMERA.GENERAL_USB)
    cameraThread=clsCamera.clsCameraThread('cameraT',camera)
    print('>> 相机初始化OK.')
    #-----------------目标检测线程--------------
    obj_detector=object_detect.ObjectDetectionExt(pbtxt_path=PBTXT_PATH,saved_model_dir=SAVED_MODEL_DIR)
    print('>> 目标检测器初始化OK.')
    #-----------------状态机线程--------------
    myFSM=fsm.clsFSMThread('fsmT',delaySeconds=0.1,dataFeeder=objectDetectorThread)
    myFSM.loadConf(confJson)
    myFSM.loadLabelClass(labelClassJson)
    #----------------Data feeder-------------
    myFeeder= mydatafeeder.DataFeeder()
    myFeeder.regist_feeder(
        'cameraThread',
        camThread,
        camThread.getNumpyImage
    )
    myFeeder.regist_processor(
        'objDetector',
        obj_detector,
        obj_detector.putImage_RGB_np,
        'cameraThread',
        obj_detector.startInfer,
        obj_detector.getResultImgAndDicts
    )
    #-------------线程启动--------------------
    cameraThread.start()
    objectDetectorThread.start()
    myFSM.start()
    myFeeder.start()
    
    print('>> Loop started.')
    print('等待初始化',end='',flush=True)
    while(1):
        #res = input('输入命令：\n')
        res='a'
        if(res.strip()=='q'.strip()):
            objectDetectorThread.exit()
            cameraThread.exit()
            print('>> Quit command received, bye.')
            break
        else:
            img=cameraThread.getNumpyImage()
            if(len(img)>1):
                objectDetectorThread.feedImage(img)
                res=objectDetectorThread.getInferenceResult() #获取预测结果

                if(len(res[0])>1):
                    #print("结果：",res[1])
                    img0=res[0] # 原始图像
                    img_markup=res[1]
                    img1=cv2.resize(img_markup,(imgW,imgH))
                    '''
                    for box in res[1]["detection_box_centers"]:
                        x=int(box[1]*imgW)
                        y=int(box[0]*imgH)
                        cv2.circle(img1,(x,y),10,(0,255,0),thickness=10)
                    '''
                    objectDetectorThread.getBoxExtFeature()
                    cv2.imshow('window',img1)
                    #myFSM.feedData(res[1])
                    #myFSM.refreshData()
                    keypressed=cv2.waitKey(1) & 0xFF
                    if keypressed == ord('q'):
                        cv2.destroyAllWindows()
                        myFeeder.exit()
                        myFSM.exit()

                        
                        cameraThread.exit()
                        break
                    elif keypressed == ord('s'):
                        fn=os.path.join('saved_img',myfunc.getNow()+'.jpg')
                        print('保存文件：',fn)
                        cv2.imwrite(fn,img0)
                else:
                    print('>',end='',flush=True)
                    pass
            else:
                print('.',end='',flush=True)
                #print(res.strip())    
    
    pass